<template>
  <div :class="{'editMode':isEdit}" class="simple-table">
    <el-table
      ref="dynamicEditRef"
      :data="listData"
      :empty-text="emptyText"
      :border="true"
      fit
      element-loading-text="加载中..."
      header-cell-class-name="dynamic-edit-table-cell"
      hightlight-current-row
    >
      <EmptyPlaceholder slot="empty" :empty-text="emptyText" is-border mode="table" style="padding-bottom: 0;" />
      <template v-for="(settingItem, index) in listSetting">
        <el-table-column
          :key="index"
          :label="settingItem.label"
          v-bind="settingItem.prop || {}"
          align="left">
          <template slot="header" slot-scope="scope">
            <div class="dynamic-table-header">
              <span v-if="isLinkRequired || (isEdit && settingItem.isRequired)" style="color: #f56c6c;margin-right:4px;">*</span>
              <span class="label">{{ scope.column.label }}</span>
              <span v-if="!isEdit && settingItem.headerCheck && !notPickPlatform" style="flex:1"/>
              <span v-if="settingItem.headerCheck">
                <span v-if="notPickPlatform" style="font-size: 12px;" class="text-red ml8">该平台暂不支持采集</span>
                <el-checkbox v-else-if="isEdit" :disabled="disabled" v-model="headerCheck[settingItem.headerCheck]" class="header-check" @change="autoPickChange(headerCheck, settingItem.headerCheck)">
                  <span>{{ settingItem.headerCheckLabel }}{{ renderHeaderCheck(headerCheck, settingItem) }}</span>
                </el-checkbox>
                <span v-else :class="headerCheck.status === 4 ? 'text-red' : 'text-blue'">{{ headerCheck.status !== 4 ? settingItem.headerCheckLabel : '' }}{{ headerCheck.status | publishStatus }}</span>
              </span>
            </div>
          </template>
          <template slot-scope="scope">
            <div
              v-if="isEdit"
              :class="{'isError': errorIds.includes(`${settingItem.keyword}.${scope.$index}`)}"
              style="padding-bottom: 1px;">
              <!-- 输入框 -->
              <el-input
                v-if="settingItem.type === 'inputText'"
                v-model="scope.row[settingItem.keyword]"
                :maxlength="settingItem.maxlength || 50"
                :placeholder="settingItem.placeholder || settingItem.label"
                :disabled="disabled"
                size="small"
                type="text"
                clearable
                @change="removeError"
              />
              <el-input
                v-if="settingItem.type === 'inputTextarea'"
                v-model="scope.row[settingItem.keyword]"
                :maxlength="settingItem.maxlength || 50"
                :placeholder="settingItem.placeholder || settingItem.label"
                :disabled="disabled"
                size="small"
                type="textarea"
                resize="none"
                clearable
                @change="removeError"
              />
              <!-- 输入区域 -->
              <el-input
                v-else-if="settingItem.type === 'textarea'"
                v-model="scope.row[settingItem.keyword]"
                :maxlength="settingItem.maxlength || 50"
                :placeholder="settingItem.placeholder || settingItem.label"
                :disabled="disabled"
                size="small"
                resize="none"
                type="textarea"
                clearable
              />
              <!-- 文件上传 -->
              <div v-if="settingItem.type === 'attachment'" class="attachment-container">
                <upAttachment
                  ref="uploadImg"
                  :file-list="scope.row[settingItem.keyword]"
                  :import-api="'/common/file/upload'"
                  :hide-confirm="true"
                  :hide-clip-up="false"
                  :extend-params="settingItem.extendParams"
                  :is-disabled="disabled"
                  :table-upload="true"
                  btn-text="上传文件"
                  @upProgress="upProgress"
                  @complateSetData="complateSetData(scope.row, settingItem.keyword, $event)"
                  @removeFileList="removeFileList(scope.row, settingItem.keyword, $event)">
                  <div class="upload-btn">
                    <i v-if="createLoading" class="el-icon-loading" style="margin-right:3px;"/>
                    <span class="content">拖拽文件或</span>
                    <span class="content-link">点击上传</span>
                    <img :src="uploadIcon" alt="">
                  </div>
                </upAttachment>
              </div>
            </div>
            <div v-else>
              <template v-if="settingItem.type === 'inputText' || settingItem.type === 'textarea' || settingItem.type === 'inputTextarea'">
                <ToolTip v-if="isLink(scope.row[settingItem.keyword])" :content="scope.row[settingItem.keyword]">
                  <a :href="scope.row[settingItem.keyword]" class="link" target="_blank">点击跳转<img :src="copyIcon" alt=""> </a>
                </ToolTip>
                <ToolTip v-else :content="scope.row[settingItem.keyword]" />
              </template>
              <FileShowList v-if="settingItem.type === 'attachment'" :file-list="scope.row[settingItem.keyword] || []" is-show-single-file />
            </div>
            <div v-if="settingItem.type === 'publishData'" class="publishData-container">
              <span v-if="!scope.row[settingItem.keyword] || isEmpty(scope.row[settingItem.keyword])" :class="{'normal-text': !isEdit}" class="placeholder-text">{{ isEdit?settingItem.placeholder:'--' }}</span>
              <publishData v-else :order-id="orderId" :data="scope.row[settingItem.keyword]" :plateform="plateform" @openChart="openChart" />
            </div>
            <div v-if="settingItem.type === 'createTime'" class="publishData-container">
              <span v-if="!scope.row[settingItem.keyword]" :class="{'normal-text': !isEdit}" class="placeholder-text">{{ isEdit?settingItem.placeholder:'--' }}</span>
              <span v-else>{{ scope.row[settingItem.keyword] | format('YYYY/MM/DD HH:mm') }}</span>
            </div>
          </template>
        </el-table-column>
      </template>
      <el-table-column
        v-if="showOperate"
        align="center"
        width="120"
        label="操作">
        <template slot-scope="scope">
          <el-button :disabled="!scope.row.publishUrl" type="text" size="small" @click="handleJump(scope.row)">采集情况</el-button>
        </template>
      </el-table-column>
    </el-table>
    <PublishChart ref="publishChartRef" :publish-url="publishUrl" />
  </div>
</template>

<script>
import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';
import uploadFile from '@/components/Common/uploadFile';
import upAttachment from '@/components/Common/upAttachment/index';
import publishData from '@/components/CreateOrder/publishData';
import FileShowList from '@/components/CreateOrder/fileShowList';
import PublishChart from '@/components/CreateOrder/orderDetail/publishChart';
import uploadIcon from '@/assets/icon-upload-blue.png';
import copyIcon from '@/assets/orderlist/copy.png';
import { format } from '@/filters/date';
import { PICK_PLATFORM } from '@/utils/const';

export default {
  name: 'SimpleTable',
  components: { FileShowList, EmptyPlaceholder, uploadFile, upAttachment, publishData, PublishChart },
  filters: {
    format,
    publishStatus(num) {
      if (!num && num !== 0) return '';
      // 采集状态 0：待采集 1：已完成 2：采集中 3：采集失败 4：连续三次采集失败
      const arr = ['待采集', '已完成', '采集中', '采集失败', '连续三次采集失败'];
      return arr[num] ? `${num !== 4 ? '：' : ''}${arr[num]}` : '';
    }
  },
  model: {
    prop: 'listData',
    event: 'changeData'
  },
  props: {
    listData: {
      type: Array,
      default: () => {
        return [];
      }
    },
    listSetting: {
      type: Array,
      default: () => {
        return [];
      }
    },
    headerCheck: {
      type: Object,
      default: () => {
        return {};
      }
    },
    isEdit: {
      type: Boolean,
      default: true
    },
    disabled: {
      type: Boolean,
      default: false
    },
    emptyText: {
      type: String,
      default: '暂无数据'
    },
    plateform: {
      type: String,
      default: ''
    },
    orderId: {
      type: String | Number,
      default: ''
    },
    publishUrl: {
      type: String,
      default: ''
    },
    getOrderInfo: {
      type: Function,
      default: null
    },
    isLinkRequired: {
      type: Boolean,
      default: false
    },
    notPickPlatform: {
      type: Boolean,
      default: false
    },
    showOperate: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      copyIcon,
      uploadIcon,
      createLoading: false,
      errorIds: []
    };
  },
  methods: {
    handleJump(row) {
      const url = this.$router.resolve({
        name: 'publish',
        query: { publishUrl: row.publishUrl }
      });
      window.open(url.href, '_blank');
    },
    changeValue() {
      this.$emit('changeData', this.listData);
    },
    validate() {
      return new Promise((resolve) => {
        const requiredKeys = this.listSetting.map(i => {
          if (i.isRequired) {
            return i.keyword;
          }
        }).filter(i => !!i);
        let isOk = true;
        const errorIds = [];
        if (Array.isArray(requiredKeys) && requiredKeys.length) {
          this.listData.forEach((data, index) => {
            requiredKeys.forEach(key => {
              if ((!data[key] && data[key] !== 0) || (Array.isArray(data[key]) && data[key].length === 0)) {
                errorIds.push(`${key}.${index}`);
                isOk = false;
              }
            });
          });
        }
        this.errorIds = errorIds;
        if (isOk) {
          resolve(true);
        } else {
          resolve(false);
        }
      });
    },
    // 上传文件
    upProgress() {
      this.createLoading = true;
    },
    complateSetData(row, key, { data, fileName }) {
      this.createLoading = false;
      const fileList = {
        name: fileName,
        url: data.url,
        time: new Date().getTime()
      };
      if (typeof data === 'string') {
        fileList.url = data;
      } else {
        fileList.url = data.url;
      }
      if (row[key]) {
        row[key].push(fileList);
      } else {
        this.$set(row, key, [fileList]);
      }
    },
    removeFileList(row, key, { file, index }) {
      row[key].splice(index, 1);
    },
    isEmpty(obj) {
      return Object.keys(obj).length === 0;
    },
    removeError() {
      this.errorIds = [];
    },
    isLink(url) {
      if (!url) return false;
      return url.indexOf('http://') === 0 || url.indexOf('https://') === 0;
    },
    openChart() {
      this.$refs.publishChartRef.openDialog(this.orderId);
    },
    renderHeaderCheck(headerCheck, settingItem) {
      if (headerCheck.status || headerCheck.status === 0) {
        if (headerCheck[settingItem.headerCheck]) {
          return this.publishSetStatus(headerCheck.status);
        }
        return ``;
      }
      return headerCheck[settingItem.headerCheck] && !this.isEdit ? '：采集中' : '';
    },
    publishSetStatus(num) {
      if (!num && num !== 0) return '';
      // 采集状态 0：待采集 1：已完成 2：采集中 3：采集失败
      const arr = ['待采集', '已完成', '采集中', '采集失败'];
      return arr[num] ? `：${arr[num]}` : '';
    },
    autoPickChange(obj, key) {
      if (!obj[key]) return;
      const info = this.getOrderInfo();
      const orderInfo = info.orderInfo;
      const type = info.type || 'create';
      const platformOption = info.platformOption || [];
      if (!orderInfo.orderPlatformId) {
        this.$message.error('请选择下单平台');
        this.$set(obj, key, false);
        return;
      }
      let name = '';
      if (type === 'create') {
        const item = platformOption.find(i => {
          return i.id === orderInfo.orderPlatformId;
        });
        if (item && item.value) name = item.value;
      } else {
        name = orderInfo.orderPlatform;
      }
      if (!PICK_PLATFORM.includes(name)) {
        this.$message.error('该平台未开通数据采集，如需采集请联系研发部');
        this.$set(obj, key, false);
        return;
      }
      if (!this.publishUrl) {
        this.$message.error('请输入发布链接');
        this.$set(obj, key, false);
        return;
      }
      this.$emit('checkLink');
    }
  }
};
</script>

<style lang="scss" scoped>
.simple-table {
  &::v-deep {
    .el-input__inner {
      &::-webkit-input-placeholder {
        color: #ddd;
      }
    }
  }
  &.editMode {
    &::v-deep {
      .fb-upload-container {
        width: 100% !important;
      }
      .file-container {
        margin-top: 0 !important;
        width: 100% !important;
      }
      tbody td {
        background-color: #fff !important;
      }
      .el-select__caret {
        color: #333;
      }
      .el-table__row {
        td {
          padding: 0;
        }
        .cell {
          padding: 0;
          .el-input__inner {
            height: 56px;
            border-radius: 0;
            border-color: transparent;
          }
          .el-textarea__inner {
            border-color: transparent;
            border-radius: 0;
          }
        }
      }
    }
  }
  .attachment-container,.publishData-container {
    padding: 10px;
  }
  .placeholder-text {
    color: #dddddd;
    font-size: 14px;
  }
  .normal-text {
    color: #333;
  }
  .upload-btn {
    display: flex;
    align-items: center;
    .content {
      color: #dddddd;
    }
    .content-link {
      color: #406EFF;
    }
    img {
      width: 16px;
      margin-left: 4px;
    }
  }
}
.isError {
  &::v-deep {
    .el-input__inner {
      border-color: red !important;
    }
    .attachment-container {
      border:1px solid red;
    }
  }
}
.dynamic-table-header {
  display: flex;
  align-items: center;
  .header-check {
    margin-left: 12px;
    display: flex;
    align-items: center;
    &::v-deep {
      .el-checkbox__label {
        padding-left: 6px;
      }
    }
  }
}
.text-blue {
  color: #406EFF;
  font-weight: normal;
}
.text-red {
  color: red;
  font-weight: normal;
}
.link {
  cursor: pointer;
  color: #406EFF;
  display: flex;
  align-items: center;
  img {
    width: 14px;
    margin-left: 4px;
  }
}
.flex {
  display: flex;
}
</style>
